Move Zeroes.

问题描述(难度简单-283)

Given an array nums, write a function to move all 0‘s to the end of it while maintaining the relative order of the non-zero elements.

Example:

1
2
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

方法一:双指针

两个index遍历,遍历到符合条件的节点互换位置。时间复杂度O(N),空间复杂度O(1)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package P283;

/**
* 双指针 时间复杂度O(N)
*/
class Solution {
public void moveZeroes(int[] nums) {
int i=0,j=1;
int mid;
while (i<nums.length && j<nums.length){
if (nums[i]==0) {
if (nums[j]!=0) {
mid=nums[i];
nums[i]=nums[j];
nums[j]=mid;
i++;j++;
}else {
j++;
}
}else {
i++;j++;
}
}

}

public static void main(String[] args) {
int[] ints={1,0};

new Solution().moveZeroes(ints);
}
}